# coding: utf-8


from flask import request, render_template

from app.op.ground_forms import SearchGroundUserForm
from app.op.models import WxUser

from . import op_bp


@op_bp.route('/ground_user/statistics', methods=['GET', 'POST'])
def ground_user_statistics():
    search_form = SearchGroundUserForm(
        True, formdata=request.form or request.args
    )
    invite_user_id = search_form.invite_user_id.data
    query = WxUser.query.filter(
        WxUser.is_ground.__eq__(True)
    ).order_by(
        WxUser.created_at.desc()
    )
    if invite_user_id:
        query = query.filter(
            WxUser.invite_user_id == invite_user_id
        )

    page = request.args.get('page', 1, type=int)
    pagination = query.paginate(
        page,
        error_out=False
    )
    users = pagination.items
    search_args = {
        key: value for key, value in search_form.data.items() if value
    }
    return render_template(
        'ground/ground_statistics.html',
        search_form=search_form,
        users=users,
        pagination=pagination,
        url_kwargs=search_args
    )
